// popup.js - 修复完整版（添加显示空字段功能）
import { FieldExtractor } from './extractor.js';
import { StorageManager } from './storage.js';

document.addEventListener('DOMContentLoaded', async () => {
  // 创建提取器实例
  const extractor = new FieldExtractor();
  
  try {
    // 初始化提取器
    await extractor.init();
    
    // 获取DOM元素
    const elements = {
      logInput: document.getElementById('logInput'),
      parseBtn: document.getElementById('parseBtn'),
      copyBtn: document.getElementById('copyBtn'),
      manageFieldsBtn: document.getElementById('manageFieldsBtn'),
      resultsContainer: document.getElementById('resultsContainer'),
      statsInfo: document.getElementById('statsInfo'),
      notification: document.getElementById('notification'),
      fieldManagerModal: document.getElementById('fieldManagerModal'),
      showEmptyFields: document.getElementById('showEmptyFields'),
      highlightImportant: document.getElementById('highlightImportant'),
      defaultFieldsList: document.getElementById('defaultFieldsList'),
      customFieldsList: document.getElementById('customFieldsList'),
      addFieldBtn: document.getElementById('addFieldBtn'),
      closeManagerBtn: document.getElementById('closeManagerBtn'),
      modalCloseBtn: document.querySelector('.modal-close')
    };
    
    // 设置默认日志
    elements.logInput.value = getDefaultLog();
    
    // 绑定事件
    elements.parseBtn.addEventListener('click', () => parseLog(extractor, elements));
    elements.copyBtn.addEventListener('click', () => copyResults(elements));
    elements.manageFieldsBtn.addEventListener('click', () => showFieldManager(extractor, elements));
    elements.closeManagerBtn.addEventListener('click', () => hideFieldManager(elements));
    elements.modalCloseBtn.addEventListener('click', () => hideFieldManager(elements));
    elements.addFieldBtn.addEventListener('click', addCustomField);
    
    // 添加显示空字段的变更监听
    elements.showEmptyFields.addEventListener('change', () => {
      // 如果有提取结果，重新渲染
      if (elements.resultsContainer.innerHTML !== '<div class="empty-result">输入日志内容后点击"提取字段"按钮</div>') {
        const logText = elements.logInput.value.trim();
        if (logText) {
          parseLog(extractor, elements);
        }
      }
    });
    
    // 初始化UI
    renderDefaultFields(extractor, elements);
    
    // 获取默认日志内容
    function getDefaultLog() {
      return `您的日志内容示例...`;
    }
    
    // 解析日志
    async function parseLog(extractor, el) {
      const logText = el.logInput.value.trim();
      
      if (!logText) {
        showNotification('请输入日志内容', 'error', el);
        return;
      }
      
      try {
        const { extractedFields, extractedCount } = extractor.extractFromText(logText);
        // 更新统计信息 - 稍后在renderResults中更新
        renderResults(extractedFields, el, extractor);
        showNotification('字段提取成功', 'success', el);
      } catch (e) {
        showNotification(`提取失败: ${e.message}`, 'error', el);
        console.error('提取错误:', e);
      }
    }
    
    // 渲染结果（已修改为支持显示空字段）
    async function renderResults(extractedFields, el, extractor) {
      const container = el.resultsContainer;
      container.innerHTML = '';
      
      const showEmpty = el.showEmptyFields.checked;
      const highlight = el.highlightImportant.checked;
      
      try {
        // 获取所有字段定义
        const allFields = extractor.getFieldsSync();
        let html = '';
        let extractedCount = 0;
        
        // 遍历所有字段定义，而不仅仅是提取到的字段
        for (const fieldDef of allFields) {
          const fieldId = fieldDef.id;
          const extractedField = extractedFields[fieldId];
          
          // 检查字段是否有值
          const hasValue = extractedField && extractedField.value;
          
          // 如果不需要显示空字段且没有值，则跳过
          if (!showEmpty && !hasValue) continue;
          
          // 获取字段值（如果有）
          const value = hasValue ? extractedField.value : '';
          
          // 标记重要字段
          const isImportant = highlight && fieldDef.important;
          
          // 处理多行字段
          const displayValue = value.replace(/\\n/g, '\n') || '<span class="empty">(空)</span>';
          
          html += `
            <div class="property-item ${isImportant ? 'important' : ''}">
              <div class="property-key">${fieldDef.name}:</div>
              <div class="property-value">${displayValue}</div>
            </div>
          `;
          
          if (hasValue) extractedCount++;
        }
        
        // 更新统计信息
        const totalFields = allFields.length;
        const emptyCount = totalFields - extractedCount;
        el.statsInfo.textContent = `${extractedCount} 个字段已提取${showEmpty ? `，${emptyCount} 个字段为空` : ''}`;
        
        container.innerHTML = html || '<div class="empty-result">未提取到有效字段</div>';
      } catch (e) {
        console.error('渲染结果失败:', e);
        container.innerHTML = '<div class="error">渲染结果失败</div>';
      }
    }
    
    // 复制结果
    function copyResults(el) {
      const items = document.querySelectorAll('.property-item');
      if (!items.length) {
        showNotification('没有内容可复制', 'error', el);
        return;
      }
      
      try {
        let text = '';
        items.forEach(item => {
          const key = item.querySelector('.property-key').textContent.replace(':', '');
          const value = item.querySelector('.property-value').textContent;
          text += `${key}: ${value}\n`;
        });
        
        navigator.clipboard.writeText(text)
          .then(() => showNotification('结果已复制到剪贴板', 'success', el))
          .catch(err => showNotification(`复制失败: ${err.message}`, 'error', el));
      } catch (err) {
        showNotification(`复制失败: ${err.message}`, 'error', el);
      }
    }
    
    // 显示字段管理器
    function showFieldManager(extractor, el) {
      el.fieldManagerModal.style.display = 'flex';
      renderDefaultFields(extractor, el);
      renderCustomFields(el);
    }
    
    // 隐藏字段管理器
    function hideFieldManager(el) {
      if (el && el.fieldManagerModal) {
        el.fieldManagerModal.style.display = 'none';
      } else {
        const modal = document.getElementById('fieldManagerModal');
        if (modal) modal.style.display = 'none';
      }
    }
    
    // 渲染内置字段
    function renderDefaultFields(extractor, el) {
      const container = el.defaultFieldsList;
      if (!container) return;
      
      container.innerHTML = '';
      
      try {
        // 使用同步方法获取字段
        const fields = extractor.getFieldsSync();
        
        fields.forEach(field => {
          const div = document.createElement('div');
          div.className = 'field-item';
          div.innerHTML = `
            <div>${field.name}</div>
            <div class="category">${field.category}</div>
          `;
          container.appendChild(div);
        });
      } catch (e) {
        console.error('渲染内置字段失败:', e);
        container.innerHTML = '<div class="error">加载字段失败</div>';
      }
    }
    
    // 渲染自定义字段
    async function renderCustomFields(el) {
      const container = el.customFieldsList;
      if (!container) return;
      
      container.innerHTML = '';
      
      try {
        const customFields = await StorageManager.get('customFields');
        
        if (!customFields || customFields.length === 0) {
          container.innerHTML = '<div class="empty">暂无自定义字段</div>';
          return;
        }
        
        customFields.forEach(field => {
          const div = document.createElement('div');
          div.className = 'field-item custom';
          div.innerHTML = `
            <div>${field.name}</div>
            <div class="actions">
              <button class="edit">编辑</button>
              <button class="delete">删除</button>
            </div>
          `;
          container.appendChild(div);
        });
      } catch (e) {
        console.error('渲染自定义字段失败:', e);
        container.innerHTML = '<div class="error">加载自定义字段失败</div>';
      }
    }
    
    // 添加自定义字段
    function addCustomField() {
      showNotification('自定义字段功能开发中', 'error', elements);
    }
    
    // 显示通知
    function showNotification(message, type = 'success', el) {
      if (!el || !el.notification) return;
      
      const notification = el.notification;
      notification.textContent = message;
      notification.className = 'notification';
      
      if (type === 'error') {
        notification.classList.add('error');
      } else {
        notification.classList.remove('error');
      }
      
      notification.classList.add('show');
      
      setTimeout(() => {
        notification.classList.remove('show');
      }, 3000);
    }
    
  } catch (error) {
    console.error('扩展初始化失败:', error);
    // 显示错误信息
    document.getElementById('resultsContainer').innerHTML = 
      `<div class="error-message">扩展初始化失败: ${error.message}</div>`;
  }
});